import logging
import threading
from datetime import datetime
import pytz
import time

initLock = threading.Lock()
rootLoggerInitialized = False

log_format = "%(asctime)s %(name)s [%(levelname)s] %(message)s"
level = logging.INFO
file_log = None  # File name
console_log = True


def init_handler(handler):
    handler.setFormatter(Formatter(log_format))


def init_logger(logger):
    logger.setLevel(level)

    if file_log is not None:
        fileHandler = logging.FileHandler(file_log)
        init_handler(fileHandler)
        logger.addHandler(fileHandler)

    if console_log:
        consoleHandler = logging.StreamHandler()
        init_handler(consoleHandler)
        logger.addHandler(consoleHandler)


def initialize():
    global rootLoggerInitialized
    with initLock:
        if not rootLoggerInitialized:
            init_logger(logging.getLogger())
            rootLoggerInitialized = True


def getLogger(name=None):
    initialize()
    return logging.getLogger(name)

default_msec_format = "%s.%03d"
# This formatter provides a way to hook in formatTime.
class Formatter(logging.Formatter):
    DATETIME_HOOK = None

    def converter(self, timestamp):
        tzinfo = pytz.timezone('Asia/Shanghai')
        dt = datetime.fromtimestamp(timestamp, tz=tzinfo)
        return dt

    def formatTime(self, record, datefmt=None):
        newDateTime = None
        if Formatter.DATETIME_HOOK is not None:
            newDateTime = Formatter.DATETIME_HOOK()

        ct = self.converter(record.created)

        if datefmt:
            s = datetime.strftime(datefmt, ct)
        else:
            t = datetime.strftime(ct, self.default_time_format)
            s = default_msec_format % (t, record.msecs)
        return s

        # if newDateTime is None:
        #     ret = super(Formatter, self).formatTime(record, datefmt)
        # else:
        #     ret = str(newDateTime)
        return ret